package com.happy_hao.msg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.happy_hao.msg.common.Result;
import com.happy_hao.msg.dto.TemplateRequest;
import com.happy_hao.msg.mapper.TemplateMapper;
import com.happy_hao.msg.po.Template;
import com.happy_hao.msg.service.TemplateService;
import com.happy_hao.msg.util.SnowFlakeUtil;
import com.happy_hao.msg.util.TemplateUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateMapper templateMapper;

    @Resource
    private TemplateUtil templateUtil;

    @Override
    public Result addTemplate(TemplateRequest templateRequest) {
        Template template = templateUtil.getTemplate(templateRequest.getTitle());
        if(template != null){
            return Result.error().message("模板已存在");
        }
        Template newTemplate = new Template();
        newTemplate.setTemplateId(SnowFlakeUtil.getSnowFlakeId());
        newTemplate.setTitle(templateRequest.getTitle());
        newTemplate.setSubject(templateRequest.getSubject());
        newTemplate.setContent(templateRequest.getContent());
        Date date = new Date();
        newTemplate.setCreateAt(date);
        newTemplate.setUpdateAt(date);
        templateMapper.insert(newTemplate);
        return Result.success();
    }

    @Override
    public Result getAllTemplate() {
        return Result.success().data("templates",templateMapper.selectList(null));
    }

    @Override
    public Result deleteTemplate(String title) {
        Template template = templateUtil.getTemplate(title);
        if(template == null){
            return Result.error().message("模板不存在");
        }
        QueryWrapper<Template> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        templateMapper.delete(queryWrapper);
        return Result.success();
    }

    @Override
    public Result updateTemplate(TemplateRequest templateRequest) {
        Template template = templateUtil.getTemplate(templateRequest.getTitle());
        if(template == null){
            return Result.error().message("您要修改的模板不存在");
        }
        UpdateWrapper<Template> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("title", templateRequest.getTitle());
        updateWrapper.set("subject", templateRequest.getSubject());
        updateWrapper.set("content", templateRequest.getContent());
        updateWrapper.set("update_at", new Date());
        templateMapper.update(null, updateWrapper);
        return Result.success().message("修改模板成功");
    }


}
